﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Cloud.Core.Model;
using Cloud.Core.Response;
using Cloud.Core.AuthUser;
using Microsoft.EntityFrameworkCore.Internal;
using Cloud.Core.Bizlogic;
using Cloud.Core.ModelSearch;
using System.Threading;

namespace Cloud.Core.Controllers
{
    /// <summary>
    /// 业务逻辑
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class BalanceController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        public BalanceController(CloudDataBase context)
        {
            _context = context;
        }

        #region base     


        #region 秤选型
        /// <summary>
        /// 秤选型
        /// </summary>
        /// by zhengyb 2020-10-14
        /// <returns></returns>
        [Route("modelSelection")]
        [HttpPost]
        public async Task<JsonResponse<DataList<Balance>>> modelSelection([FromHeader] string Authorization, [FromBody] sModelParam sModelParam)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<Balance>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //} 
            response.Data = new DataList<Balance>();
            var listQuery = _context.Balance.Where(t => 1 == 1);
            if (!string.IsNullOrEmpty(sModelParam.structure))
            {
                listQuery = listQuery.Where(t => t.structure == sModelParam.structure);
            }
            if (!string.IsNullOrEmpty(sModelParam.calcAccuracy))
            {
                listQuery = listQuery.Where(t => t.calcAccuracy == sModelParam.calcAccuracy);
            }
            if (!string.IsNullOrEmpty(sModelParam.calcWidth))
            {
                listQuery = listQuery.Where(t => t.maxWidth >=Convert.ToInt32(sModelParam.calcWidth) && t.minWidth <= Convert.ToInt32(sModelParam.calcWidth));
            }
            if (!string.IsNullOrEmpty(sModelParam.structureEasy))
            {
                listQuery = listQuery.Where(t => t.structureEasy == sModelParam.structureEasy);
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                 .OrderByDescending(t => t.Model)
                 .ToArrayAsync()
                 .ConfigureAwait(false);

            response.Msg = "查询成功";
            response.Data.Count = list.Length;
            response.Data.List = list;
            response.Status = ResponseStatus.Success;
            return response;
        }

        #endregion  

        #region 获取分页信息
        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<Balance>>> GetList([FromHeader] string Authorization, sPage sPage)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<Balance>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            response.Data = new DataList<Balance>();

            new Helper().sPageNew(sPage);
            var listQuery = _context.Balance.Where(t => 1 == 1);
            if (!string.IsNullOrEmpty(sPage.Field1))
            {
                listQuery = listQuery.Where(t => t.Model.Contains(sPage.Field1));
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                   .OrderByDescending(t => t.Id)
                   .Skip((int)sPage.PageIndex * (int)sPage.PageSize)
                   .Take((int)sPage.PageSize)
                   .ToArrayAsync()
                   .ConfigureAwait(false);
            response.Data.Count = list.Length;
            response.Data.List = list;
            response.Msg = "查询成功";
            response.Status = ResponseStatus.Success;

            //------------------------------------------------
            //_context.Balance.OrderByDescending(s => s.RealName);
            //_context.Balance.OrderBy(s => s.CreateDate);
            //------------------------------------------------
            return response;
        }
        #endregion

        #region 设备添加
        /// <summary>
        /// 设备添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Route("BalanceAdd")]
        [HttpPost]
        public async Task<JsonResponse> BalanceAdd([FromHeader] string Authorization, Balance entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }

            var data = await _context.Balance.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (data != null)
            {
                response.Msg = "添加失败,该设备已存在";
                response.Status = ResponseStatus.MultipleData;
                return response;
            }
            var arr = _context.Balance.Select(t => t.Id).ToArray();


            _context.Set<Balance>().Add(entity);
            //int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "设备添加成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "添加失败";
                response.Status = ResponseStatus.ParameterError;
            }
            string et = response.Msg + "-实体内容:" + new Helper().ObjectToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));


            return response;
        }
        #endregion

        #region 设备编辑
        /// <summary>
        /// 设备编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("BalanceUpdate")]
        public async Task<JsonResponse> BalanceUpdate([FromHeader] string Authorization, Balance entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var dataCount = _context.Set<Balance>().Where(c => c.Id == entity.Id).Count();

            //var data = await _context.Balance.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (dataCount == 0)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            _context.Set<Balance>().Update(entity);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "设备修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "修改失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));

            return response;
        }

        #endregion

        #region 设备删除
        /// <summary>
        /// 设备删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("BalanceDel")]
        public async Task<JsonResponse> BalanceDel([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            string[] arr = ids.TrimEnd(',').Split(',');
            Guid[] barr = new Guid[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                barr[i] = new Guid(arr[i]);
            }
            var Balances = _context.Balance.Where(c => barr.Contains(c.Id));

            var dataCount = Balances.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(Balances);

            _context.Balance.RemoveRange(Balances);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "设备删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "设备删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion        
        #endregion
    }
}
